package com.engine.ld.optimize;

import com.weaver.general.BaseBean;
import org.dom4j.DocumentException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;

/**
 * @author ZhangLei
 * @date 2021/6/24
 * 库存查询
 */
public class Kccx {
    private static final BaseBean bb = new BaseBean();

    public String doKccx(String matnr,String werks) throws DocumentException, ParserConfigurationException {
//        组装返回的xml
        //        组装XML并返回
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.newDocument();
        org.w3c.dom.Element root = document.createElement("ROOT");
        document.appendChild(root);

        appendChild(document,root,"MATNR", matnr);
        appendChild(document,root,"ZMATNR", "");
        appendChild(document,root,"WERKS", werks);
        appendChild(document,root,"ZWERKS", "");
        appendChild(document,root,"LGORT", "");
        appendChild(document,root,"ZLGORT", "");
        appendChild(document,root,"CHARG", "");
        appendChild(document,root,"ZCHARG", "");
        appendChild(document,root,"MTART", "");
        appendChild(document,root,"ZMTART", "");
        appendChild(document,root,"MATKL", "");
        appendChild(document,root,"ZMATKL", "");
        appendChild(document,root,"ZPCBX", "");


        bb.writeLog("result: " + xmlHeadStr() + createXmlToString(document) + xmlTailStr());

        return xmlHeadStr() + createXmlToString(document) + xmlTailStr();
    }

    /**
     * 去除<_--5CTYPE_--3DSTRING>之前部分，去除</_--5CTYPE_--3DSTRING>之后部分
     * @param xml xml字符串
     * @return 去除头尾部分的xml字符串
     * */
    private String getRealXml(String xml){
        if(!xml.contains("<_--5CTYPE_--3DSTRING>")) {
            return xml;
        }
        int start = xml.indexOf("<_--5CTYPE_--3DSTRING>") + "<_--5CTYPE_--3DSTRING>".length();
        int end = xml.indexOf("</_--5CTYPE_--3DSTRING>");
        return xml.substring(start, end).trim();
    }

    /**
     * document对象中添加子项
     * @param document ducument对象
     * @param parent 父元素
     * @param key 元素标签
     * @param value 元素content值
     */
    private static void appendChild(org.w3c.dom.Document document, org.w3c.dom.Element parent, String key, String value) {
        org.w3c.dom.Element child = document.createElement(key);
        if(child != null) {
            child.setTextContent(value);
        }
        parent.appendChild(child);
    }

    /**
     * xml固定头部
     */
    private static String xmlHeadStr() {
        return "<asx:abap version=\"1.0\" xmlns:asx=\"http://www.sap.com/abapxml\">\n" +
                "\t<asx:values>\n" +
                "\t\t<_--5CTYPE_--3DSTRING>\n";
    }

    /**
     * xml固定尾部
     */
    private static String xmlTailStr() {
        return "\t\t</_--5CTYPE_--3DSTRING>\n" +
                "\t</asx:values>\n" +
                "</asx:abap>";
    }

    /**
     * 生成xml字符串
     * @param document Document树对象
     * @return 整个xml字符串
     */
    private static String createXmlToString(org.w3c.dom.Document document){
        String xmlString = null;
        try {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            xmlString = bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}
